import 'dart:convert';
import 'package:encrypt/encrypt.dart';
import 'package:flutter/services.dart';
import 'package:pointycastle/asymmetric/api.dart';

class RsaUtil {
  static late Encrypter _encrypter;

  static Encrypter get encrypter => _encrypter;

  static init() async {
    final pubkStr =
        await rootBundle.loadString("assets/file/rsa_public_key.pem");
    // final pvk = RSAKeyParser().parse(pvkStr) as RSAPrivateKey;
    final pubk = RSAKeyParser().parse(pubkStr) as RSAPublicKey;

    _encrypter = Encrypter(RSA(publicKey: pubk));
  }

  static encryptText(String text) {
    const mlen = 117;
    final bytes = utf8.encode(text);

    var offset = 0;
    List<int> buffer = [];
    while (offset < bytes.length) {
      var len = bytes.length - offset;
      len = len > mlen ? mlen : len;

      final sub = bytes.sublist(offset, offset + len);
      buffer.addAll(encrypter.encryptBytes(sub).bytes);
      offset += len;
    }
    return base64Encode(buffer);
  }
}
